package sadi.server;

import java.util.Date;
import java.awt.*;
import java.awt.event.*;
import java.net.MalformedURLException;
import java.rmi.*;

import javax.swing.*;

public class ServerGUI extends JFrame
{
	//GUI Instance Variables
	private JTextArea log;
	private JScrollPane scrollLog;
	private JButton resetlog;
	
	public ServerGUI()
	{
		//Set Up GUI
		log = new JTextArea();
		scrollLog = new JScrollPane(log);
	    add(scrollLog, BorderLayout.CENTER);
	    
	    resetlog = new JButton("Clear Server Log");
	    resetlog.addActionListener	(
	    								new ActionListener()
	    								{
	    									public void actionPerformed(ActionEvent e)
	    									{
	    										int confirm = JOptionPane.showConfirmDialog(null, 
	    													  "Are you sure you want to clear the log?", "Clear Server Log", JOptionPane.YES_NO_OPTION);

	    										if(confirm == JOptionPane.YES_OPTION)
	    											log.setText("");
	    									}
	    								}
	    							);
	    add(resetlog, BorderLayout.SOUTH);
	    
	    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
	    setSize(500, 500);
	    setTitle("WikiServer");
	    setVisible(true);
	}
	
	//Helper Function to Write Log Messages to GUI TextArea
	public void appendLog(boolean hasDate, Object message)
	{
		//Add Date/Time prefix to message
		String prefix = (hasDate)? new Date() + ": " : "";		
		log.append(prefix + message);
	}
	
	public static void main(String [] args)
	{
		//Construct GUI
		ServerGUI serverGUI = new ServerGUI();
		serverGUI.appendLog(true, "Server UI Initialized.\n");
		
		//Set Security Manager
		System.setSecurityManager(new RMISecurityManager());
		
		try
		{
			//Construct & Rebind Server
			WikiServerImpl server = new WikiServerImpl(serverGUI);
			Naming.rebind("rmi://localhost:1099/WikiServer", server);
			serverGUI.appendLog(true, "Registered WikiServer to RMI Registry.\n\n");
		}
		catch(RemoteException e)
		{
			e.printStackTrace();
		}
		catch(MalformedURLException e)
		{
			e.printStackTrace();
		}		
	}
}
